<template>
  <view class="shop-container">
    <!-- 固定顶部区域 -->
    <view class="fixed-top">
      <!-- 顶部搜索框 -->
      <view class="search-header">
        <view class="search-box">
          <view class="search-input-wrapper">
            <image src="/static/search.svg" class="search-icon"></image>
            <input 
              class="search-input" 
              type="text" 
              v-model="searchQuery" 
              placeholder="输入商品名称" 
              confirm-type="search"
            />
            <text 
              v-if="searchQuery" 
              class="clear-icon" 
              @click="clearSearch"
            >×</text>
          </view>
        </view>
      </view>
      
      <!-- 分类筛选栏 -->
      <scroll-view class="filter-scroll" scroll-x="true" show-scrollbar="false" enhanced="true">
        <view class="filter-container">
          <view 
            v-for="filter in filters" 
            :key="filter.id" 
            class="filter-item"
            @click="toggleFilter(filter.id)"
          >
            <text class="filter-text">{{ filter.name }}</text>
            <view class="arrow-down" v-if="filter.id !== 'gpu'"></view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 可滚动内容区域 -->
    <scroll-view class="scrollable-content" scroll-y="true" enhanced="true">
    
      <!-- 筛选面板遮罩层 -->
      <view v-if="activeFilter" class="filter-mask" @click="closeFilterPanel"></view>
    
      <!-- 筛选面板 -->
      <view v-if="activeFilter" class="filter-panel">
        <view class="filter-options">
          <view 
            v-for="option in getFilterOptions(activeFilter)" 
            :key="option.id" 
            class="filter-option"
            :class="{ selected: isOptionSelected(activeFilter, option.id) }"
            @click="selectOption(activeFilter, option.id)"
          >
            <text>{{ option.name }}</text>
            <text v-if="isOptionSelected(activeFilter, option.id)" class="check-icon">✓</text>
          </view>
        </view>
        <!-- 底部按钮 -->
        <view class="action-buttons">
          <button class="reset-button" @click="resetFilters">重置</button>
          <button class="confirm-button" @click="applyFilters">确定</button>
        </view>
      </view>
      
      <view class="swiper-container">
        <swiper class="swiper" circular autoplay interval="3000" duration="500" indicator-dots indicator-active-color="#ff8c00">
          <swiper-item v-for="(item, index) in bannerList" :key="index">
            <image :src="item.imageUrl" mode="aspectFill" class="swiper-image"></image>
          </swiper-item>
        </swiper>
      </view>

      <view class="tab-container">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'buy' }" 
          @click="switchTab('buy')"
        >
          <view class="tab-icon-wrapper">
            <text class="tab-icon-text">🛍️</text>
          </view>
          <view class="tab-content">
            <text class="tab-text">我要买酒</text>
            <text class="tab-subtext">Buy wine</text>
          </view>
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'sell' }" 
          @click="switchTab('sell')"
        >
          <view class="tab-icon-wrapper">
            <text class="tab-icon-text">💰</text>
          </view>
          <view class="tab-content">
            <text class="tab-text">我要卖酒</text>
            <text class="tab-subtext">Sell wine</text>
          </view>
        </view>
      </view>

      <!-- 表格内容区域 -->
      <view class="table-container" v-if="activeTab === 'buy' && buyProducts && buyProducts.length > 0">
        <!-- 买酒表格 -->
        <view class="table-header">
          <view class="th product">商品</view>
          <view class="th">单瓶价</view>
          <view class="th">原箱价</view>
        </view>
        <view class="table-body">
          <view class="table-row" v-for="(item, index) in buyProducts" :key="index">
            <view class="td product">
              <image :src="item.image[0]" class="product-image"></image>
              <text>{{ item.name }}</text>
            </view>
            <view class="td">{{ item.singlePrice }}</view>
            <view class="td">{{ item.boxPrice }}</view>
          </view>
        </view>
      </view>

      <!-- 买酒：无数据占位 -->
      <view class="empty-state" v-if="activeTab === 'buy' && (!buyProducts || buyProducts.length === 0)">
        <text class="empty-icon">📦</text>
        <text class="empty-text">暂无商品</text>
      </view>

      <view class="table-container" v-if="activeTab === 'sell' && sellProducts && sellProducts.length > 0">
        <!-- 卖酒表格 -->
        <view class="table-header">
          <view class="th product">商品</view>
          <view class="th">单品回收价</view>
          <view class="th">估值</view>
        </view>
        <view class="table-body">
          <view class="table-row" v-for="(item, index) in sellProducts" :key="index">
            <view class="td product">
              <image :src="item.image[0]" class="product-image"></image>
              <text>{{ item.name }}</text>
            </view>
            <view class="td">{{ item.recyclePrice }}</view>
            <view class="td">{{ item.evaluation }}</view>
          </view>
        </view>
      </view>

      <!-- 卖酒：无数据占位 -->
      <view class="empty-state" v-if="activeTab === 'sell' && (!sellProducts || sellProducts.length === 0)">
        <!-- <text class="empty-icon">📦</text> -->
        <text class="empty-text">暂无商品</text>
      </view>
      
      <!-- 底部分享图标 -->
      <button open-type="share" class="share-button">
        <view class="share-icon-container">
          <view class="share-icon-circle">
            <text class="share-icon">分享</text>
          </view>
        </view>
      </button>
      
      <!-- 用户信息授权弹框 -->
      <view v-if="showUserInfoAuth" class="global-modal-overlay">
        <view class="global-modal">
          <text class="modal-title">需要授权用户信息</text>
          <text class="modal-desc">用于完善会员资料与个性化服务</text>
          <view class="modal-actions">
            <!-- #ifdef MP-WEIXIN -->
            <button class="primary" @tap="getUserProfile">去授权</button>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
            <button class="primary" @tap="showPhoneAuthTip">去授权</button>
            <!-- #endif -->
            <button class="secondary" @tap="showUserInfoAuth=false">稍后</button>
          </view>
        </view>
      </view>
      
      <!-- 手机号授权弹框（由 App.vue 触发显示） -->
      <view v-if="showPhoneAuth" class="global-modal-overlay">
        <view class="global-modal">
          <text class="modal-title">需要授权手机号</text>
          <text class="modal-desc">用于联系与交易服务</text>
          <view class="modal-actions">
            <!-- #ifdef MP-WEIXIN -->
            <button class="primary" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">去授权</button>
            <!-- #endif -->
            <!-- #ifndef MP-WEIXIN -->
            <button class="primary" @tap="showPhoneAuthTip">去授权</button>
            <!-- #endif -->
            <button class="secondary" @tap="showPhoneAuth=false">稍后</button>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script>
import { getCategoryTree, getAdvertList, getProductList, getPhoneNumberByCode, addUser } from '@/api/getApiResult.js';

export default {
  data() {
    return {
      searchQuery: '',
      activeFilter: null,
      activeTab: 'buy', // 默认选中"我要买酒"
      showUserInfoAuth: false, // 是否显示用户信息授权弹框
      showPhoneAuth: false, // 是否显示手机号授权
      phoneNumber: '', // 已授权手机号（如果有）
      bannerList: [
        { imageUrl: 'https://picsum.photos/800/400?random=1' },
        { imageUrl: 'https://picsum.photos/800/400?random=2' },
        { imageUrl: 'https://picsum.photos/800/400?random=3' }
      ],
      filters: [], // 从API获取的分类数据
      filterOptions: {}, // 从API获取的子分类数据
      selectedOptions: {},
      // 完整商品数据，用于搜索过滤
      allBuyProducts: [],
      allSellProducts: [],
      // 分类映射，用于筛选匹配
      categoryIdNameMap: {},
      optionIdNameMap: {},
      // 买酒表格数据
      buyProducts: [],
      // 卖酒表格数据
      sellProducts: []
    }
  },
  watch: {
    // 搜索词变化时，实时应用模糊过滤
    searchQuery() {
      this.applySearchFilter();
    }
  },
  onLoad() {
    // 页面加载时获取分类数据
    this.loadCategoryTree();
    // 加载广告列表
    this.loadAdvertList();
    // 加载商品列表
    this.loadProductList();
    // 初始化手机号（仅读取，不弹窗）
    this.loadPhoneNumber();
  },
  onShow() {
    // 监听 App.vue 发出的显示用户信息授权弹框事件
    this._showUserInfoAuthHandler = () => {
      console.log('收到显示用户信息授权弹框事件');
      this.showUserInfoAuth = true;
    };
    uni.$on('show-user-info-auth', this._showUserInfoAuthHandler);
    
    // 监听 App.vue 发出的显示手机号授权弹框事件
    this._showPhoneAuthHandler = () => {
      console.log('收到显示手机号授权弹框事件');
      this.showPhoneAuth = true;
    };
    uni.$on('show-phone-auth', this._showPhoneAuthHandler);
    
    // 监听 App.vue 发出的手机号授权成功事件
    this._phoneAuthSuccessHandler = (data) => {
      if (data && data.code) {
        console.log('收到手机号授权成功事件, code:', data.code);
        // 直接发送 code 到后端获取手机号
        this.sendCodeToServer(data.code);
      }
    };
    uni.$on('phone-auth-success', this._phoneAuthSuccessHandler);
  },
  onHide() {
    if (this._showUserInfoAuthHandler) {
      uni.$off('show-user-info-auth', this._showUserInfoAuthHandler);
      this._showUserInfoAuthHandler = null;
    }
    if (this._showPhoneAuthHandler) {
      uni.$off('show-phone-auth', this._showPhoneAuthHandler);
      this._showPhoneAuthHandler = null;
    }
    if (this._phoneAuthSuccessHandler) {
      uni.$off('phone-auth-success', this._phoneAuthSuccessHandler);
      this._phoneAuthSuccessHandler = null;
    }
  },
  methods: {
    // 仅加载手机号，不触发弹窗（弹窗由 App.vue 控制）
    loadPhoneNumber() {
      try {
        const phone = uni.getStorageSync('phoneNumber');
        if (phone) {
          this.phoneNumber = phone;
        }
      } catch (e) {
        console.error('读取手机号失败', e);
      }
    },
    // 测试轮播图显示
    testBannerDisplay() {
      console.log('测试轮播图显示...');
      console.log('当前bannerList:', this.bannerList);
      
      // 设置测试数据
      const testData = [
        { imageUrl: 'https://picsum.photos/800/400?random=test1', description: '测试广告1', id: '1', name: '测试1' },
        { imageUrl: 'https://picsum.photos/800/400?random=test2', description: '测试广告2', id: '2', name: '测试2' }
      ];
      
      this.bannerList = testData;
      console.log('已设置测试轮播图数据:', this.bannerList);
      
      // 强制更新视图
      this.$forceUpdate();
    },
    
    // 加载商品列表
    async loadProductList() {
      try {
        const response = await getProductList();
        console.log('商品列表接口返回数据:', response);
        
        // 获取商品数据 - 支持多种数据格式
        let products = [];
        
        // 如果返回的是标准格式 {code: 0, data: [...]}
        if (response && (response.code === 0 || response.code === 200) && response.data) {
          products = response.data;
        }
        // 如果直接返回数组
        else if (Array.isArray(response)) {
          products = response;
        }
        
        // 处理商品数据
        if (products && products.length > 0) {
          // 买酒数据 - 使用售卖价格
          const mappedBuy = products.map(item => ({
            name: item.name || '',
            image: (item.image && Array.isArray(item.image) && item.image.length > 0) ? item.image[0] : 'https://picsum.photos/100/100?random=' + Math.random(),
            singlePrice: item.singleBottleSellingPrice ? `${item.singleBottleSellingPrice}元` : '暂无价格',
            boxPrice: item.originalBoxSellingPrice ? `${item.originalBoxSellingPrice}元` : '暂无价格',
            change: 0,
            // 供模糊查询使用的分类字段
            firstCategory: item.firstCategory || '',
            secondCategory: item.secondCategory || ''
          }));
          
          // 卖酒数据 - 使用回收价格
          const mappedSell = products.map(item => ({
            name: item.name || '',
            image: (item.image && Array.isArray(item.image) && item.image.length > 0) ? item.image[0] : 'https://picsum.photos/100/100?random=' + Math.random(),
            recyclePrice: item.singleBottleRecyclingPrice ? `${item.singleBottleRecyclingPrice}元` : '暂无价格',
            evaluation: item.statusName || '待评估',
            // 供模糊查询使用的分类字段
            firstCategory: item.firstCategory || '',
            secondCategory: item.secondCategory || ''
          }));
          
          // 保存完整数据供搜索过滤使用
          this.allBuyProducts = mappedBuy;
          this.allSellProducts = mappedSell;

          // 初次显示应用搜索过滤（若有输入）
          this.applySearchFilter();
          
          console.log('买酒商品数量:', this.allBuyProducts.length);
          console.log('卖酒商品数量:', this.allSellProducts.length);
        }
      } catch (error) {
        console.error('加载商品列表失败:', error);
        // 保持默认数据
      }
    },

    // 模糊查询：依据搜索词在商品名称、一级分类、二级分类进行匹配
    applySearchFilter() {
      const q = (this.searchQuery || '').trim().toLowerCase();
      const sourceBuy = (this.allBuyProducts && this.allBuyProducts.length) ? this.allBuyProducts : this.buyProducts;
      const sourceSell = (this.allSellProducts && this.allSellProducts.length) ? this.allSellProducts : this.sellProducts;

      // 选中的二级分类名称集合
      const selectedNames = new Set();
      const selectedIds = new Set();
      Object.keys(this.selectedOptions || {}).forEach(parentId => {
        const ids = this.selectedOptions[parentId] || [];
        ids.forEach(id => {
          const name = this.optionIdNameMap[id];
          if (name) selectedNames.add(String(name).toLowerCase());
          selectedIds.add(String(id).toLowerCase());
        });
      });
      // 当前展开的一级分类名称（无选中子项时也可按一级分类过滤）
      const activeParentName = this.activeFilter ? (this.categoryIdNameMap[this.activeFilter] || '').toLowerCase() : '';
      const activeParentId = this.activeFilter ? String(this.activeFilter).toLowerCase() : '';
      
      console.log('筛选条件:', {
        searchQuery: q,
        activeParentName,
        activeParentId,
        selectedNames: Array.from(selectedNames),
        hasActiveFilter: !!this.activeFilter,
        hasSelectedOptions: selectedNames.size > 0
      });

      const matchCombined = (item) => {
        const name = (item.name || '').toLowerCase();
        const fc = (item.firstCategory || '').toLowerCase();
        const sc = (item.secondCategory || '').toLowerCase();

        // 搜索词匹配（为空则视为通过）
        const searchPass = !q || name.includes(q) || fc.includes(q) || sc.includes(q);

        // 分类匹配规则：
        // - 若有选中的二级分类，则 secondCategory 命中其一即可
        // - 否则若当前展开了某一级分类，则按一级分类匹配
        // - 都没有则视为通过（显示所有商品）
        let categoryPass = true;
        if (selectedNames.size > 0) {
          // 有选中的二级分类
          const scLower = sc;
          const fcLower = fc;
          categoryPass = Array.from(selectedNames).some(n => scLower.includes(n))
            || Array.from(selectedIds).some(id => String(item.secondCategory || '').toLowerCase() === id);
        } else if (activeParentName && this.activeFilter) {
          // 只展开了一级分类，但没有选中二级分类
          // 这种情况下应该显示所有商品，不做过滤
          categoryPass = true;
        }

        return searchPass && categoryPass;
      };

      this.buyProducts = sourceBuy.filter(matchCombined);
      this.sellProducts = sourceSell.filter(matchCombined);
      
      console.log('筛选结果:', {
        buyProductsCount: this.buyProducts.length,
        sellProductsCount: this.sellProducts.length
      });
    },
    
    // 加载广告列表
    async loadAdvertList() {
      try {
        const response = await getAdvertList();
        console.log('广告接口返回数据:', response);
        
        // 获取图片数据 - 支持多种数据格式
        let images = [];
        
        // 如果返回的是标准格式 {code: 0, data: [...]}
        if (response && (response.code === 0 || response.code === 200) && response.data) {
          images = response.data;
        }
        // 如果直接返回数组
        else if (Array.isArray(response)) {
          images = response;
        }
        
        // 提取所有图片地址
        if (images && images.length > 0) {
          const imageUrls = [];
          images.forEach(item => {
            // 支持 images 字段（数组或字符串）
            if (item.images) {
              if (Array.isArray(item.images)) {
                imageUrls.push(...item.images);
              } else if (typeof item.images === 'string') {
                imageUrls.push(item.images);
              }
            }
            // 支持 image 字段（数组或字符串）
            else if (item.image) {
              if (Array.isArray(item.image)) {
                imageUrls.push(...item.image);
              } else if (typeof item.image === 'string') {
                imageUrls.push(item.image);
              }
            }
          });
          
          // 如果有图片地址，更新轮播图
          if (imageUrls.length > 0) {
            this.bannerList = imageUrls.map(url => ({
              imageUrl: url,
              description: '',
              id: '',
              name: ''
            }));
            console.log('轮播图已更新，图片数量:', this.bannerList.length);
          }
        }
      } catch (error) {
        console.error('加载广告数据失败:', error);
      }
    },
    
    // 加载分类树数据
  async loadCategoryTree() {
    try {
      console.log('开始加载分类数据...');
      const response = await getCategoryTree();
      console.log('分类数据返回:', response);
      console.log('分类数据类型:', typeof response);
      console.log('分类数据是否为数组:', Array.isArray(response));
      console.log('分类数量:', response && response.data ? response.data.length : 0);
      
      // 检查是否是标准API响应格式
      if (response && response.code === 200 && response.data && Array.isArray(response.data)) {
        console.log('标准API格式，分类数据有效，开始处理');
        console.log('第一个分类示例:', response.data[0]);
        this.processCategoryData({ data: response.data });
      } else if (response && Array.isArray(response)) {
        // 兼容数组格式
        console.log('数组格式，分类数据有效，开始处理');
        console.log('第一个分类示例:', response[0]);
        this.processCategoryData({ data: response });
      } else {
        console.error('分类数据格式错误或数据为空:', response);
        this.loadDefaultCategories();
      }
    } catch (error) {
      console.error('加载分类数据失败:', error);
      // 如果API调用失败，使用默认数据
      this.loadDefaultCategories();
    }
  },
    
    // 处理分类数据
    processCategoryData(categoryData) {
      if (!categoryData || !categoryData.data) {
        this.loadDefaultCategories();
        return;
      }
      
      const categories = categoryData.data;
      console.log('开始处理分类数据，数量:', categories.length);
      console.log('第一个分类数据:', categories[0]);
      
      this.filters = [];
      this.filterOptions = {};
      this.categoryIdNameMap = {};
      this.optionIdNameMap = {};
      
      categories.forEach((category, index) => {
        console.log(`处理第${index + 1}个分类:`, category);
        
        // 添加主分类
        this.filters.push({
          id: category.id,
          name: category.name,
          expanded: false
        });
        this.categoryIdNameMap[category.id] = category.name;
        
        // 处理子分类 - 如果存在 children 数组
        if (category.children && category.children.length > 0) {
          console.log(`分类 ${category.name} 有 ${category.children.length} 个子分类`);
          this.filterOptions[category.id] = category.children.map(child => ({
            id: child.id,
            name: child.name
          }));
          // 记录子分类 id->name 映射
          category.children.forEach(child => {
            this.optionIdNameMap[child.id] = child.name;
          });
        } else {
          console.log(`分类 ${category.name} 没有子分类`);
        }
      });
      
      console.log('最终filters:', this.filters);
      console.log('最终filterOptions:', this.filterOptions);
    },
    
    // 加载默认分类数据（API失败时使用）
    loadDefaultCategories() {
      this.filters = [
        { id: 'mt', name: '茅台', expanded: false },
        { id: 'gcmj', name: '国产名酒', expanded: false },
        { id: 'hyj', name: '红洋酒', expanded: false },
        { id: 'gdlp', name: '高端礼品', expanded: false }
      ];
      this.categoryIdNameMap = {
        mt: '茅台',
        gcmj: '国产名酒',
        hyj: '红洋酒',
        gdlp: '高端礼品'
      };
      this.filterOptions = {
        mt: [
          { id: 'nianfen', name: '年份酒' },
          { id: 'shengxiao', name: '生肖酒' },
          { id: 'dingzhi', name: '定制酒' }
        ],
        gcmj: [
          { id: 'wuliangye', name: '五粮液' },
          { id: 'jiannanchun', name: '剑南春' },
          { id: 'guojiao', name: '国窖1573' },
          { id: 'luzhou', name: '泸州老窖' },
          { id: 'yanghe', name: '洋河' },
          { id: 'fenjiu', name: '汾酒' }
        ],
        hyj: [
          { id: 'hongjiu', name: '红酒品牌' },
          { id: 'yangjiu', name: '洋酒品牌' }
        ],
        gdlp: [
          { id: 'yanwo', name: '燕窝' },
          { id: 'chongcao', name: '虫草' }
        ]
      };
      // 构建子分类映射
      this.optionIdNameMap = {};
      Object.keys(this.filterOptions).forEach(pid => {
        this.filterOptions[pid].forEach(opt => {
          this.optionIdNameMap[opt.id] = opt.name;
        });
      });
    },
    
    // 检查手机号授权
    checkPhoneAuth() {
      const phoneNumber = uni.getStorageSync('phoneNumber');
      if (!phoneNumber && this.activeTab === 'sell') {
        // 如果是卖酒标签且没有手机号授权，跳转到授权页面
        uni.navigateTo({
          url: '/pages/auth/phone?redirect=' + encodeURIComponent('/pages/shop/index')
        });
      }
    },
    
    shareToWechat() {
      // 使用小程序原生分享能力
      uni.showToast({
        title: '点击右上角分享给好友',
        icon: 'none',
        duration: 2000
      });
    },
    
    // 定义页面的分享信息（小程序专用）
    onShareAppMessage() {
      return {
        title: '酒类回购小程序 - 优质酒类交易平台',
        path: '/pages/shop/index',
        imageUrl: '/static/logo.png'
      };
    },
    
    clearSearch() {
      this.searchQuery = '';
      // 清除搜索后恢复完整列表
      this.applySearchFilter();
    },
    toggleFilter(filterId) {
      if (this.activeFilter === filterId) {
        this.activeFilter = null;
      } else {
        this.activeFilter = filterId;
      }
      
      // 更新展开状态
      this.filters.forEach(filter => {
        filter.expanded = filter.id === this.activeFilter;
      });
      // 修改：切换分类时不筛选，只展开下拉选项
      // this.applySearchFilter();
    },
    getFilterOptions(filterId) {
      return this.filterOptions[filterId] || [];
    },
    isOptionSelected(filterId, optionId) {
      if (!this.selectedOptions[filterId]) {
        return false;
      }
      return this.selectedOptions[filterId].includes(optionId);
    },
    selectOption(filterId, optionId) {
      if (!this.selectedOptions[filterId]) {
        this.selectedOptions[filterId] = [];
      }
      
      const index = this.selectedOptions[filterId].indexOf(optionId);
      if (index > -1) {
        this.selectedOptions[filterId].splice(index, 1);
      } else {
        this.selectedOptions[filterId].push(optionId);
      }
      // 修改：不立即筛选，等待点击确定按钮
      // this.applySearchFilter();
    },
    resetFilters() {
      this.selectedOptions = {};
      this.activeFilter = null;
      this.filters.forEach(filter => {
        filter.expanded = false;
      });
      // 重置后恢复完整列表
      this.applySearchFilter();
    },
    applyFilters() {
      this.activeFilter = null;
      this.filters.forEach(filter => {
        filter.expanded = false;
      });
      // 点击确定后应用所有筛选条件
      this.applySearchFilter();
    },
    closeFilterPanel() {
      // 点击遮罩层时关闭筛选面板
      this.activeFilter = null;
      this.filters.forEach(filter => {
        filter.expanded = false;
      });
    },
    switchTab(tab) {
      // 仅切换标签，不再初始化手机号授权
      this.activeTab = tab;
    },
    
    // 非微信环境提示
    showPhoneAuthTip() {
      uni.showToast({ title: '请在微信小程序内授权', icon: 'none' });
    },
    
    // 获取用户信息
    getUserProfile() {
      // #ifdef MP-WEIXIN
      if (typeof uni.getUserProfile === 'function') {
        uni.getUserProfile({
          desc: '用于完善会员资料',
          success: (res) => {
            console.log('获取用户信息成功:', res);
            try {
              uni.setStorageSync('userInfo', JSON.stringify(res.userInfo || res));
              this.showUserInfoAuth = false;
              uni.showToast({ title: '授权成功', icon: 'success' });
              // 通知 App.vue 用户信息授权成功
              const app = getApp();
              if (app && app.handleUserInfoSuccess) {
                app.handleUserInfoSuccess();
              }
            } catch (e) {
              console.error('保存用户信息失败:', e);
              uni.showToast({ title: '保存用户信息失败', icon: 'none' });
            }
          },
          fail: (err) => {
            console.error('获取用户信息失败:', err);
            uni.showToast({ title: '获取用户信息失败', icon: 'none' });
          }
        });
      } else {
        uni.showToast({ title: '当前环境不支持获取用户信息', icon: 'none' });
      }
      // #endif
      // #ifndef MP-WEIXIN
      uni.showToast({ title: '请在微信小程序内授权', icon: 'none' });
      // #endif
    },
    
    // 获取手机号回调
    getPhoneNumber(e) {
      if (e.detail.errMsg === 'getPhoneNumber:ok') {
        // 用户同意授权
        const code = e.detail.code;
        // 发送code到后端换取手机号
        this.sendCodeToServer(code);
      } else {
        // 用户拒绝授权
        uni.showToast({
          title: '需要授权手机号才能使用卖酒功能',
          icon: 'none',
          duration: 2000
        });
      }
      // 隐藏授权按钮
      this.showPhoneAuth = false;
    },
    
    // 发送code到后端换取手机号
    async sendCodeToServer(code) {
      console.log('code', code);
      uni.showLoading({ title: '获取中...' });
      try {
        const res = await getPhoneNumberByCode(code);
        uni.hideLoading();
        // 兼容返回结构，优先读取标准返回 { phoneNumber }
        let phoneNumber = (res && typeof res === 'object' && 'phoneNumber' in res)
          ? res.phoneNumber
          : (res?.data?.phoneNumber ?? res?.phoneNumber ?? res?.data?.phone ?? res?.phone ?? res?.phone_info?.phoneNumber ?? res?.data?.phone_info?.phoneNumber);
        console.log('手机号解析结果:', phoneNumber, '原始响应:', res);
        if (phoneNumber) {
          uni.setStorageSync('phoneNumber', phoneNumber);
          this.phoneNumber = phoneNumber; // 更新当前页面的手机号数据
          this.showPhoneAuth = false;
          // 读取用户信息并同步到后台新增用户
          let userInfoRaw = null; let userInfo = null;
          try { userInfoRaw = uni.getStorageSync('userInfo'); } catch(e) {}
          try { userInfo = typeof userInfoRaw === 'string' ? JSON.parse(userInfoRaw) : userInfoRaw; } catch(e) {}
          const payload = {
            address: '',
            gender: userInfo.gender === 0 ? '男' : '女',
            nickname: userInfo?.nickName || userInfo?.nickname || '',
            tel: phoneNumber,
            visitCount: 0
          };
          try {
            await addUser(payload);
            console.log('新增用户成功', payload);
          } catch(err) {
            console.error('新增用户失败', err);
          }
          uni.showToast({
            title: '授权成功',
            icon: 'success',
            duration: 2000
          });
        } else {
          uni.showToast({
            title: '获取手机号失败',
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('获取手机号失败', error);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none',
          duration: 2000
        });
      }
    },

    // 用户信息
   getUserInfo(e) {
    uni.getUserProfile({
      desc: '用于完善会员资料',
      success: res => {
        console.log('用户信息：', res)
        this.userInfo = res.userInfo
      },
      fail: err => {
        console.log('用户拒绝授权', err)
      }
    })
  },
  }
}
</script>

<style>
.shop-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
  position: relative;
  padding-top: 60px; /* 固定顶部区域 */
}

.fixed-top {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background-color: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  height: auto;
}

.scrollable-content {
  flex: 1;
  height: calc(100vh - 90px); /* 减去固定顶部区域的高度 */
  margin-top: 36px; /* 不需要额外的顶部边距，因为已经在shop-container中设置了padding-top */
  padding-bottom: 20px; /* 底部留出一些空间 */
  overflow-y: auto;
  -webkit-overflow-scrolling: touch; /* 增强iOS滚动体验 */
}

/* 顶部搜索框样式 */
.search-header {
  display: flex;
  align-items: center;
  padding: 12px 15px 10px;
  background-color: #ff8c00;
  border-bottom: 1px solid #f0f0f0;
  position: relative;
  z-index: 1001;
}

.back-icon {
  font-size: 24px;
  color: #fff;
  margin-right: 5px;
}

.search-box {
  flex: 1;
  width: 90%;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 16px;
  height: 36px;
  width: 100%;
}

.search-icon {
  width: 16px;
  height: 16px;
  margin-left: 10px;
}

  .search-input {
  flex: 1;
  height: 36px;
  font-size: 13px;
  border: none;
  padding: 0 5px;
}

.clear-icon {
  font-size: 16px;
  color: #999;
  padding-right: 12px;
  font-weight: bold;
}
/* 授权覆盖层样式 */
.global-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}
.global-modal {
  width: 80%;
  max-width: 340px;
  background: #fff;
  border-radius: 16px;
  padding: 32px 24px 24px;
  box-shadow: 0 12px 40px rgba(0,0,0,0.15);
  text-align: center;
}
.modal-title {
  display: block;
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 12px;
  line-height: 1.4;
}
.modal-desc {
  display: block;
  font-size: 14px;
  color: #888;
  margin-bottom: 28px;
  line-height: 1.6;
}
.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
}
.modal-actions .primary {
  flex: 1;
  background: linear-gradient(135deg, #ff8c00 0%, #ff6600 100%);
  color: #fff;
  border-radius: 18px;
  padding: 8px 20px;
  border: none;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 4px 12px rgba(255, 140, 0, 0.3);
  transition: all 0.3s;
}

.modal-actions .primary::after {
  border: none;
}

.modal-actions .secondary {
  flex: 1;
  background: #f5f5f5;
  color: #666;
  border-radius: 18px;
  padding: 8px 20px;
  border: none;
  font-size: 14px;
  font-weight: 400;
}

.modal-actions .secondary::after {
  border: none;
}
/* 分类筛选栏样式 */
.filter-scroll {
  width: 100%;
  height: 36px;
  white-space: nowrap;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  -webkit-overflow-scrolling: touch; /* 增强iOS滚动体验 */
  position: relative;
  z-index: 1001;
}

.filter-container {
  display: flex;
  padding: 0;
  width: 100%;
  justify-content: space-between;
  height: 100%;
}

.filter-item {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  font-size: 13px;
  color: #666;
  flex: 1;
  text-align: center;
  white-space: nowrap;
  height: 100%;
}

.filter-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 80px; /* 限制最大宽度 */
}

.arrow-down {
  margin-left: 3px;
  width: 0;
  height: 0;
  border-left: 4px solid transparent;
  border-right: 4px solid transparent;
  border-top: 4px solid #999;
  display: inline-block;
}

/* 分享按钮样式 */
.share-button {
  position: fixed;
  bottom: 100px; /* 调整底部距离，避免与底部导航栏重叠 */
  right: 20px;
  z-index: 300;
  width: 50px;
  height: 50px;
}

.share-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
}

.share-icon-circle {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  background-color: #FFA500;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
}

.share-icon {
  color: #fff;
  font-size: 24rpx;
  font-weight: bold;
  text-align: center;
}

/* 手机号授权按钮样式 */
.phone-auth-button {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 0;
  padding: 0;
  margin: 0;
  opacity: 0;
  z-index: -1;
}

/* 筛选面板遮罩层 */
.filter-mask {
  position: fixed;
  top: 96px;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 199;
}

/* 筛选面板样式 */
.filter-panel {
  background-color: #fff;
  padding: 8px;
  border-bottom: 1px solid #eee;
  position: fixed;
  top: 96px;
  left: 0;
  right: 0;
  z-index: 200; /* 确保显示在最上层，高于固定顶部的z-index */
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  max-height: 60vh; /* 限制最大高度 */
  overflow-y: auto; /* 内容过多时可滚动 */
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
}

.filter-option {
  width: 46%;
  margin: 2%;
  padding: 8px;
  font-size: 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-sizing: border-box;
}

.filter-option.selected {
  color: #ff8c00;
  background-color: rgba(255, 140, 0, 0.1);
  border: 1px solid #ff8c00;
  border-radius: 4px;
}

.check-icon {
  color: #ff8c00;
  font-weight: bold;
  margin-right: 4px;
}

/* 底部按钮样式 */
.action-buttons {
  display: flex;
  justify-content: space-between;
  padding: 12px;
  background-color: #fff;
  border-top: 1px solid #eee;
  width: 100%;
  box-sizing: border-box;
}

.reset-button, .confirm-button {
  width: 45%;
  height: 36px;
  line-height: 36px;
  border-radius: 18px;
  font-size: 14px;
  text-align: center;
  padding: 0;
  border: none;
}

.reset-button::after, .confirm-button::after {
  border: none;
}

.reset-button {
  background-color: #fff;
  color: #ff8c00;
  border: 1px solid #ff8c00;
}

.confirm-button {
  background-color: #ff8c00;
  color: #fff;
}

/* 轮播图样式 */
.swiper-container {
  width: 100%;
  padding: 0;
  margin-top: -10px; /* 减少与筛选栏的距离 */
  background-color: #fff;
}

.swiper {
  height: 180px;
  width: 100%;
  margin-bottom: 10px; /* 添加底部间距 */
}

.swiper-image {
  width: 100%;
  height: 100%;
  border-radius: 8px;
}

/* 标签按钮样式 */
.tab-container {
  display: flex;
  justify-content: space-between;
  padding: 15px;
  background-color: #fff;
  margin-top: 10px;
  gap: 20px; /* 增加标签之间的间距 */
}

.tab-item {
  display: flex;
  align-items: center;
  width: 46%; /* 减小宽度以增加间距 */
  padding: 12px 15px;
  border-radius: 10px;
  background-color: #f5f5f5;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.tab-item.active {
  background-color: #fff8f0;
  border: 1px solid #ff8c00;
}

.tab-icon {
  width: 30px;
  height: 30px;
  margin-right: 10px;
}

.tab-icon-wrapper {
  width: 50px;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 140, 0, 0.1);
  border-radius: 50%;
  margin-right: 12px;
}

.tab-icon-text {
  font-size: 28px;
}

.tab-content {
  display: flex;
  flex-direction: column;
}

.tab-text {
  font-size: 14px;
  font-weight: bold;
  margin-bottom: 2px;
}

.tab-item.active .tab-text {
  color: #ff8c00;
}

.tab-subtext {
  font-size: 11px;
  color: #666;
}

.tab-item.active .tab-subtext {
  color: #ff8c00;
}

.tab-item.active::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background-color: #ff8c00;
}

/* 表格样式 */
.table-container {
  margin: 12px 8px;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  background-color: #fff;
}

/* 无数据占位 */
.empty-state {
  margin: 60px auto;
  padding: 40px 20px;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  font-size: 60px;
  margin-bottom: 16px;
  opacity: 0.6;
}

.empty-text {
  font-size: 15px;
  color: #999;
  font-weight: 400;
}

.table-header {
  display: flex;
  background-color: #f0f0f0;
  color: #333;
  font-weight: bold;
  padding: 10px 0;
  border-bottom: 1px solid #e0e0e0;
  font-size: 13px;
}

.table-body {
  background-color: #fff;
  padding: 3px 0;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.table-row:last-child {
  border-bottom: none;
}

.th, .td {
  flex: 1;
  text-align: center;
  padding: 0 8px;
  font-size: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.th.product, .td.product {
  flex: 2;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  text-align: left;
  padding-left: 12px;
}

.product-image {
  width: 32px;
  height: 32px;
  margin-right: 10px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.change {
  padding: 4px 8px;
  border-radius: 6px;
  font-size: 12px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
}

.change.positive {
  background-color: rgba(76, 175, 80, 0.15);
  color: #4caf50;
}

.change.negative {
  background-color: rgba(244, 67, 54, 0.15);
  color: #f44336;
}

.arrow {
  margin-left: 4px;
}

/* 分享按钮样式 */
.share-button {
  position: fixed;
  right: 15px;
  bottom: 80px;
  background: none;
  border: none;
  padding: 0;
  margin: 0;
  z-index: 100;
}

.share-button::after {
  border: none;
}

/* 测试按钮样式 */
.test-button {
  position: fixed;
  left: 15px;
  bottom: 80px;
  background: #007aff;
  color: white;
  border: none;
  padding: 10px 15px;
  border-radius: 20px;
  font-size: 12px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.test-button::after {
  border: none;
}

.share-icon-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.share-icon-circle {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #ff8c00;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.share-icon {
  color: white;
  font-size: 14px;
  font-weight: bold;
}
</style>